/**********************************************************************************************************************
* COPYRIGHT 
* ------------------------------------------------------------------------------------------------------------------- 
* Copyright (c) iSOFT INFRASTRUCTURE SOFTWARE CO., LTD. This software is proprietary to 
* iSOFT INFRASTRUCTURE SOFTWARE CO., LTD., and all rights are reserved by iSOFT INFRASTRUCTURE SOFTWARE CO., LTD. 
* Without the express written permission of the company, no organization or individual may copy, install, trial, 
* distribute, or reverse engineer this software. For terms of use and further details, please refer to the End User 
* License Agreement (EULA) or contact us business@i-soft.com.cn for more assistance. 
* 
* This file contains code from EasyXMen, which is licensed under the LGPL-2.1. However, due to a special exception, 
* you are not required to comply with the provisions of section 6a of LGPL-2.1. Specifically, you may distribute 
* your software, including this file, under terms of your choice, including proprietary licenses, without needing to 
* provide the source code or object code as specified in section 6a. For more details, please refer to the project's 
* LICENSE and EXCEPTION files and the specific exception statement.  
* ------------------------------------------------------------------------------------------------------------------- 
* FILE DESCRIPTION 
* ------------------------------------------------------------------------------------------------------------------- 
*  @MCU                : S32K148 
*  @file               : Os_UserInf.c 
*  @license            : Evaliation 
*  @licenseExpiryDate  :  
*  @date               : 2024-10-21 10:37:16 
*  @customer           : EasyXMen User 
*  @toolVersion        : 2.0.18 
*********************************************************************************************************************/ 

/*=======[I N C L U D E S]====================================================*/
#include "Os.h"
#include "Arch_Extend.h"
#include "Arch_Processor.h"
/** DO NOT CHANGE THIS COMMENT!
 * <USERBLOCK User Includes>
 */
/* custom code.... */
#include <stdio.h>
#include <string.h>
#include "Gpt.h"
#include "Can_43_FLEXCAN.h"
#include "Mem_43_INFLS.h"
#include "MemAcc.h"
#include "EcuM.h"
#include "EcuM_Cbk.h"
#include "ComM.h"
#include "ComM_Gent.h"
#include "NvM.h"
#include "WdgM.h"
#include "Fee.h"
#include "Dem.h"
#include "MemIf_Types.h"
#include "SchM_Fee.h"
#include "SchM_MemAcc.h"
#include "SchM_CanSM.h"
#include "SchM_CanNm.h"
#include "SchM_NvM.h"
#include "SchM_Com.h"
#include "SchM_CanTp.h"
#include "SchM_Dcm.h"
#include "SchM_EcuM.h"
#include "SchM_BswM.h"
#include "SchM_Dem.h"
#include "SchM_WdgM.h"
#include "CryIf.h"
#include "Crypto.h"
#include "Csm.h"
#include "Csm_Cfg.h"
#include "SM2.h"
/** DO NOT CHANGE THIS COMMENT!
 * </USERBLOCK User Includes>
 */
/*=======[V E R S I O N   I N F O R M A T I O N]===============================*/
#define     OS_USERAPP_C_AR_MAJOR_VERSION              19U
#define     OS_USERAPP_C_AR_MINOR_VERSION              11U
#define     OS_USERAPP_C_AR_PATCH_VERSION              0U
#define     OS_USERAPP_C_SW_MAJOR_VERSION              2U
#define     OS_USERAPP_C_SW_MINOR_VERSION              0U
#define     OS_USERAPP_C_SW_PATCH_VERSION              0U

/*=======[V E R S I O N  C H E C K]===========================================*/
#if (OS_USERAPP_C_AR_MAJOR_VERSION != OS_CFG_H_AR_MAJOR_VERSION)
    #error "Os_Userapp.c:Mismatch in Specification Major Version"
#endif
#if (OS_USERAPP_C_AR_MINOR_VERSION != OS_CFG_H_AR_MINOR_VERSION)
    #error "Os_Userapp.c:Mismatch in Specification Minor Version"
#endif
#if (OS_USERAPP_C_AR_PATCH_VERSION != OS_CFG_H_AR_PATCH_VERSION)
    #error "Os_Userapp.c:Mismatch in Specification Patch Version"
#endif
#if (OS_USERAPP_C_SW_MAJOR_VERSION != OS_CFG_H_SW_MAJOR_VERSION)
    #error "Os_Userapp.c:Mismatch in Specification Major Version"
#endif
#if (OS_USERAPP_C_SW_MINOR_VERSION != OS_CFG_H_SW_MINOR_VERSION)
    #error "Os_Userapp.c:Mismatch in Specification Minor Version"
#endif

/*=======[T A S K S]==========================================*/
/* PRQA S 1532++ */ /* MISRA Rule 8.7 */

void debug_sig_info(uint64 signatureCost, uint64 verifCost, char *digestPtr, char *sigPtr, char *sigRPtr, char *sigSPtr) {

}

void debug_encrypt_info(uint64 encryptCost, uint64 decryptCost, char *cipherBuf) {

}

uint64 TimerCountMs = 0;

/*OsTask_Init: Core0(CPU0),Type = BASIC, Priority = 1*/
TASK(OsTask_Init)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK OsTask_Init >
    */
    /* custom code.... */
	uint32 NVM_USE_InitTIME = 0;
	uint32 INIT_READALL_TIMEOUT = 15000;
	NvM_RequestResultType InitNvMReadAllStatus = NVM_REQ_NOT_OK;

	EcuM_StartupTwo();

	Mem_43_INFLS_Init(NULL_PTR);
	MemAcc_Init(&MemAcc_Config);
	Fee_Init(NULL_PTR);
	NvM_Init(NULL_PTR);

	NvM_ReadAll();
	do
	{
		NVM_USE_InitTIME++;
		NvM_MainFunction();
		Fee_MainFunction();
		MemAcc_MainFunction();
		Mem_43_INFLS_MainFunction();
		NvM_GetErrorStatus(0,&InitNvMReadAllStatus);
		if(INIT_READALL_TIMEOUT < NVM_USE_InitTIME)
			break;
	}while(InitNvMReadAllStatus == NVM_REQ_PENDING);

	Dem_Init(&DemPbCfg);
	// initialization
	CryIf_Init(NULL_PTR);
	Csm_Init(NULL_PTR);
	Crypto_Init(NULL_PTR);

    EcuM_SetWakeupEvent(EcuMWakeupSource_CAN);
    ComM_RequestComMode(0, COMM_FULL_COMMUNICATION);
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK OsTask_Init >
    */
    if (E_OK != TerminateTask())
    {
        while (1)
        {
            /* dead loop */
        }
    }
}

/*OsTask_1ms: Core0(CPU0),Type = BASIC, Priority = 4*/
TASK(OsTask_1ms)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK OsTask_1ms >
    */
    /* custom code.... */
	CanSM_MainFunction();
	static uint32 num = 0;
	TimerCountMs++;
	if (++num > 400) {
		num = 0;
		WdgM_CheckpointReached(WdgMSupervisedEntity_0, SE0_WdgMCheckpoint_0);
		WdgM_MainFunction();
	}
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK OsTask_1ms >
    */
    if (E_OK != TerminateTask())
    {
        while (1)
        {
            /* dead loop */
        }
    }
}

/*OsTask_5ms: Core0(CPU0),Type = BASIC, Priority = 3*/
TASK(OsTask_5ms)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK OsTask_5ms >
    */
    /* custom code.... */
    CanNm_MainFunction();
    ComM_MainFunction_Channel_CanController_0();
    Com_MainFunctionRx();
    Com_MainFunctionTx();

    CanTp_MainFunction();
	Dcm_MainFunction();

	uint8 input[] =
			"7C93AA2CB289D3639453CE12408F81295333528D0481163C76C92C2ED5A28F4846E63BC46A17AD1F894D48F71ADD661C00529B961C6D86E7B4B0E60246F0D814100762ACA15F89C78126C54AC7CBF742391B65C70C9D827EB99C33AE14F6D2660A80D3CDB372D142D4C9FD158D7722F81C7441213AF3159C53417D10692FD6043A792CA66CBD014AE0CEC76918F774F4EBA750D68F88D5413D54AE08C9B1A8F7D7A61B9C59E163A14D9BF99F472013C2E6E2E76FD885B682B135D90F2F4945E99489AA807FDD8D24745B2623C253BF55C3DE6A91A612A5979090EF7D804D0451EA5A2B1F23A3E97204246FB3FEFECBF1BCEFA42F447DA263289C84856A3ED5DCBEBBEA1C9FF986C0B44508EB8B04309F7228A8BE63D3212DAA17C7E8E2EE7644C5F31B7ACD7AF4E98C03BAB754B7CC742641BBA73E397D3B828B1CA20C749727BD3BDC45ACEEC18B82D476AA27ED36A61295AD914E0A69ED24726FDF2DF63A1D7EA8997558CA9DD9C44E15F1F40B5061A29FA7E43BD87F47069D420675C84B8CA5037C20BA1759CC3F8224392B3BF586BB429A38830CB8191550312ADBBF12B18F537D3FC5F40EF6F4D72A2F4245AE3F30F2654EB4C5C68F527612D976D901B7BD8AEB5E8E9071B91C22A3039531A3BCE0FF1D8DF55542AF9D2D147552E5771C3879E4407B0E86FD3012BDFA725E3BDD4233F8EA2A914D0006DC93D832DE11C7060EB2D9F90CAE502672EF8EAC2A31BD3B3594230CAA92DB6D0066FFA6C2A8E20EF56E2695EE5BC017D18A4F00A68F4C260BD672E2C5B8DF4CBB70C64A5E03032E50AB9E997A0F1FB0C498328EA6E7856A3FFBBA5F467745DBE1460EA785C61B4B07FE39E661A5B8F62C145E534EFF7D06CC343A6D49DF0CB2057D41897C024A1FBCA4857553ED498DEACF1923F0A2A8155FAB0AC5CB2C7837170E0871DF4895C1D0032DF7881F0C5F2BD493223F73BA21465FE34344FF705C88F5A7CE9D997E21CD365D21BB59F5B6B8A89C49EE7A8C68A93F43CDC69CF7A9BC61EB3225648E5B4D90AB136D8259D3B0606FC0B48F6ACC0FE232323F21D137E8C906BE5FDCC73401C2234CC4955ED9EA3D1906605DAC788EFF8A8649E8CE0B887E58164DB6FF5C23A95177E62D504D6C158A3F39F40587A317FDD63E1DC698222CA1CF5901B9F8BFE2E5B373DD2EBCCCA7FD8C1D58B9DF5B7DBEC250098144DCC759563FCA64674D75A6524F6F7E8DAD5870953C6DD11E0FD73680C837908FF07A95D891C151D8F4F5C84C26ECD672D2E5B390E335CBF25855C23B15BC3448BD916EF21528A457C3795F985AF1867685096504C87B60E7574E04A6E0E546588F471E3B77B2D4690030298D67FDEA7C52CE2FEC54AEFB4FFB5981AB44CCD196C2E0192053FC6A01EB372E61FBA5EAE26A4F2E32D295DADF189FEDD14A1F03C568B3D12C09E927";
	uint8 userId[] = "1234567812345678";
	uint8 privateKeyBuf[] =
			"59A408B5ED69E2EBE8DC3DD4621453DA8B0DEBF294190ACD9CDB452E90B7763D";
	uint8 publicKeyBuf[] =
			"2EB5019334A21AE618570009491C50B3C17D6E6B6B9CDEAF7E924B5004852252CE93DF59CFB607B4ED46A654341F4636C12333C3FA13E28F5B7404A30C0AFA84";

	uint32 userIdLen = (uint32) strlen((const char*) userId);
	uint32 privateKeyHexLen = (uint32) strlen((const char*) privateKeyBuf);
	uint32 publicKeyHexLen = (uint32) strlen((const char*) publicKeyBuf);
	uint32 inputHexLen = (uint32) strlen((const char*) input);
	uint32 inputLen = inputHexLen / 2;

	uint8 privateKey[32] = { 0 };
	uint8 publicKey[64] = { 0 };
	uint8 sig[64] = { 0 };
	uint32 sigLen = 64;
	uint8 digest[32] = { 0 };
	uint32 digestLen = 32;
	uint64 signatureStartMs;
	uint64 signatureEndMs;
	uint64 signatureCostMs = 0;

	uint64 verifStartMs;
	uint64 verifEndMs;
	uint64 verifCostMs = 0;

	char digestBuf[128];
	char sigBuf[256];
	char sigRBuf[128];
	char sigSBuf[128];

	// read data
	sm2_hex2bin((const char*) privateKeyBuf, privateKeyHexLen, privateKey);
	sm2_hex2bin((const char*) publicKeyBuf, publicKeyHexLen, publicKey);
	sm2_hex2bin((const char*) input, inputHexLen, input);

	Crypto_OperationModeType operate = CRYPTO_OPERATIONMODE_SINGLECALL;

	// SM2 signature generate test
	signatureStartMs = TimerCountMs;
	Std_ReturnType ret = E_NOT_OK;
	// set private key
	ret = Crypto_KeyElementSet(0, CRYPTO_KE_SIGNATURE_KEY,
			privateKey, 32);

	if (E_OK == ret) {
		// set public key
		ret = Crypto_KeyElementSet(1, CRYPTO_KE_SIGNATURE_KEY,
				publicKey, 64);
	}

	if (E_OK == ret) {
		// enable private key
		ret = Crypto_KeySetValid(0);
	}
	if (E_OK == ret) {
		// enable public key
		ret = Crypto_KeySetValid(1);
	}
	if (E_OK == ret) {
		ret = Csm_SignatureGenerateExtend(CsmJob_gen_sig, operate, input,
				inputLen, userId, userIdLen, sig, &sigLen, digest, &digestLen);
	}
	if (E_OK == ret) { // SM2 signature generate success
		signatureEndMs = TimerCountMs;

		// SM2 signature verify test
		verifStartMs = TimerCountMs;
		Crypto_VerifyResultType verifRet;

		ret = Csm_SignatureVerifyExtend(CsmJob_var_sig, operate, input,
				inputLen, userId, userIdLen, sig, sigLen, &verifRet);
		if (ret == E_OK && CRYPTO_E_VER_OK == verifRet) { // SM2 signature verify success
			verifEndMs = TimerCountMs;

			signatureCostMs = signatureEndMs - signatureStartMs;
			verifCostMs = verifEndMs - verifStartMs;

			// show signature info
			char *tmpPtr = digestBuf;
			tmpPtr += sprintf(tmpPtr, "digest: ");
			for (int i = 0; i < 32; ++i) {
				tmpPtr += sprintf(tmpPtr, "%02X", digest[i]);
			}
			tmpPtr += sprintf(tmpPtr, "\n");
			tmpPtr = sigBuf;
			tmpPtr += sprintf(tmpPtr, "Signature(ASN.1): %02X%02X", 0x04, 64);
			for (int i = 0; i < 64; ++i) {
				tmpPtr += sprintf(tmpPtr, "%02X", sig[i]);
			}
			tmpPtr += sprintf(tmpPtr, "\n");
			tmpPtr = sigRBuf;
			tmpPtr += sprintf(tmpPtr, "Signature R: ");
			for (int i = 0; i < 32; ++i) {
				tmpPtr += sprintf(tmpPtr, "%02X", sig[i]);
			}
			tmpPtr += sprintf(tmpPtr, "\n");
			tmpPtr = sigSBuf;
			tmpPtr += sprintf(tmpPtr, "Signature S: ");
			for (int i = 32; i < 64; ++i) {
				tmpPtr += sprintf(tmpPtr, "%02X", sig[i]);
			}
			tmpPtr += sprintf(tmpPtr, "\n");

			debug_sig_info(signatureCostMs, verifCostMs, digestBuf, sigBuf, sigRBuf, sigSBuf); // Add breakpoint on this line
		}
	}


	uint8 input_data[] =
			"966397a223d8521deec7a9c256ba70b53e313fb056e962a35738561eb5b8f4cc322c2433c9ddbcc1b3d13a44a979808db5afc6b43bf43e90fca3ce9f294fce82";
	uint8 cipher[256] = { 0 };
	uint8 plain[256] = { 0 };
	uint8 *c1 = cipher;
	uint8 *c3 = c1 + 64;
	uint8 *c2 = c3 + 32;
	char cipherBuf[512] = { 0 };
	uint32 cipherLen = 256;
	uint32 plainLen = 256;

	uint64 encryptStartMs;
	uint64 encryptEndMs;
	uint64 encryptCostMs = 0;

	uint64 decryptStartMs;
	uint64 decryptEndMs;
	uint64 decryptCostMs = 0;

	uint32 inputDataHexLen = (uint32) strlen((const char*) input_data);
	uint32 inputDataLen = inputDataHexLen / 2;
	// read data
	sm2_hex2bin((const char*) input_data, inputDataHexLen, input_data);

	// encrypt test
	encryptStartMs = TimerCountMs;
	ret = Csm_Encrypt(CsmJob_encrypt, operate, input_data, inputDataLen, cipher, &cipherLen);
	if (E_OK == ret) {
		encryptEndMs = TimerCountMs;
		// decrypt test
		decryptStartMs = TimerCountMs;
		ret = Csm_Decrypt(CsmJob_decrypt, operate, cipher, cipherLen, plain, &plainLen);
		if (E_OK == ret && 0 == memcmp(plain, input_data, plainLen)) {
			decryptEndMs = TimerCountMs;

			encryptCostMs = encryptEndMs - encryptStartMs;
			decryptCostMs = decryptEndMs - decryptStartMs;
			char *tmpPtr = cipherBuf;
			tmpPtr += sprintf(tmpPtr, "Cipher Text: ");
			for (int i = 0; i < cipherLen; ++i) {
				tmpPtr += sprintf(tmpPtr, "%02X", cipher[i]);
			}
			tmpPtr += sprintf(tmpPtr, "\n");
			debug_encrypt_info(encryptCostMs, decryptCostMs, cipherBuf); // Add breakpoint on this line
		}
	}

    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK OsTask_5ms >
    */
    if (E_OK != TerminateTask())
    {
        while (1)
        {
            /* dead loop */
        }
    }
}

/*OsTask_10ms: Core0(CPU0),Type = BASIC, Priority = 2*/
TASK(OsTask_10ms)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK OsTask_10ms >
    */
    /* custom code.... */
    EcuM_MainFunction();
    BswM_MainFunction();
    Dem_MainFunction();

    NvM_MainFunction();
    Fee_MainFunction();
	MemAcc_MainFunction();
	Mem_43_INFLS_MainFunction();
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK OsTask_10ms >
    */
    if (E_OK != TerminateTask())
    {
        while (1)
        {
            /* dead loop */
        }
    }
}

/*OsTask_100ms: Core0(CPU0),Type = BASIC, Priority = 1*/
TASK(OsTask_100ms)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK OsTask_100ms >
    */
    /* custom code.... */
	WdgM_CheckpointReached(WdgMSupervisedEntity_0, SE0_WdgMCheckpoint_0);
	WdgM_MainFunction();

    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK OsTask_100ms >
    */
    if (E_OK != TerminateTask())
    {
        while (1)
        {
            /* dead loop */
        }
    }
}

/*=======[H O O K S]================================================*/
FUNC(void, OS_APPL_CODE) IdleHook_Core0(void)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK IdleHook_Core0>
    */
    /* custom code.... */
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK IdleHook_Core0>
    */
}

/*=======[ALARM CALL BACK]==========================================*/

FUNC(void, OS_APPL_CODE) ErrorHook(StatusType Error)
{
    /***The code below is just for deleting the complier warning.***
    ***Please remove it and use your own code****/
    (void)Error;
    /***The code above is just for deleting the complier warning*/
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK ErrorHook>
    */
    /* custom code.... */
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK ErrorHook>
    */
}

FUNC(void, OS_APPL_CODE) StartupHook(void)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK StartupHook>
    */
    /* custom code.... */
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK StartupHook>
    */
}

FUNC(void, OS_APPL_CODE) ShutdownHook(StatusType Error)
{
    /***The code below is just for deleting the complier warning.***
    ***Please remove it and use your own code****/
    (void)Error;
    /***The code above is just for deleting the complier warning*/
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK ShutdownHook>
    */
    /* custom code.... */
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK ShutdownHook>
    */
}

/*=======[P A N I C H A N D L E R]================================*/
FUNC(void, OS_CODE) Arch_PanicHandler(void)
{
    /* please insert your code here ... */
}

/*=======[I S R S]================================================*/
/*
 *ISR(CAN0_ORed: Core0(CPU0))
 */
ISR(CAN0_ORed)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK CAN0_ORed>
    */
    /* custom code.... */
	extern void CAN0_ORED_IRQHandler();
	CAN0_ORED_IRQHandler();
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK CAN0_ORed>
    */
}

/*
 *ISR(CAN0_ORed_0_15_MB: Core0(CPU0))
 */
ISR(CAN0_ORed_0_15_MB)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK CAN0_ORed_0_15_MB>
    */
    /* custom code.... */
	extern void CAN0_ORED_0_15_MB_IRQHandler();
	CAN0_ORED_0_15_MB_IRQHandler();
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK CAN0_ORed_0_15_MB>
    */
}

/*
 *ISR(CAN0_ORed_16_31_MB: Core0(CPU0))
 */
ISR(CAN0_ORed_16_31_MB)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK CAN0_ORed_16_31_MB>
    */
    /* custom code.... */
	extern void CAN0_ORED_16_31_MB_IRQHandler();
	CAN0_ORED_16_31_MB_IRQHandler();
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK CAN0_ORed_16_31_MB>
    */
}

/*
 *ISR(FTM0_Ch0_Ch1: Core0(CPU0))
 */
ISR(FTM0_Ch0_Ch1)
{
    /* please insert your code here ... */
    /** DO NOT CHANGE THIS COMMENT!
    * <USERBLOCK FTM0_Ch0_Ch1>
    */
    /* custom code.... */
	extern void FTM_0_CH_0_CH_1_ISR();
	FTM_0_CH_0_CH_1_ISR();
    /** DO NOT CHANGE THIS COMMENT!
    * </USERBLOCK FTM0_Ch0_Ch1>
    */
}

/* PRQA S 1532-- */ /* MISRA Rule 8.7 */
/*=======[E N D   O F   F I L E]==============================================*/

